import { createStore } from 'vuex'

export default createStore({
  state: {
    // 用户相关状态
    user: null,
    isLoggedIn: false,
    
    // 管理员相关状态
    admin: null,
    isAdminLoggedIn: false,
    
    // 购物车
    cart: [],
    
    // 结算商品
    checkoutItems: [],
    
    // 商品分类
    categories: [],
    
    // 当前页面加载状态
    loading: false
  },
  
  getters: {
    // 获取用户信息
    currentUser: state => state.user,
    
    // 检查是否登录
    isUserLoggedIn: state => state.isLoggedIn,
    
    // 获取管理员信息
    currentAdmin: state => state.admin,
    
    // 检查是否为管理员
    isAdminLoggedIn: state => state.isAdminLoggedIn,
    
    // 获取购物车商品数量
    cartItemCount: state => {
      return state.cart.reduce((total, item) => total + item.quantity, 0)
    },
    
    // 获取购物车总价
    cartTotalPrice: state => {
      return state.cart.reduce((total, item) => total + (item.price * item.quantity), 0)
    },
    
    // 获取选中的购物车商品
    selectedCartItems: state => {
      return state.cart.filter(item => item.selected)
    },
    
    // 获取商品分类
    productCategories: state => state.categories
  },
  
  mutations: {
    // 设置用户信息
    setUser(state, user) {
      state.user = user
      state.isLoggedIn = !!user
      // 保存到localStorage
      if (user) {
        localStorage.setItem('user', JSON.stringify(user))
      } else {
        localStorage.removeItem('user')
      }
    },
    
    // 更新用户信息
    updateUser(state, userData) {
      if (state.user) {
        state.user = { ...state.user, ...userData }
        localStorage.setItem('user', JSON.stringify(state.user))
      }
    },
    
    // 设置管理员信息
    setAdmin(state, admin) {
      state.admin = admin
      state.isAdminLoggedIn = !!admin
      // 保存到localStorage
      if (admin) {
        localStorage.setItem('admin', JSON.stringify(admin))
      } else {
        localStorage.removeItem('admin')
      }
    },
    
    // 用户登出
    logout(state) {
      state.user = null
      state.isLoggedIn = false
      localStorage.removeItem('user')
    },
    
    // 管理员登出
    adminLogout(state) {
      state.admin = null
      state.isAdminLoggedIn = false
      localStorage.removeItem('admin')
    },
    
    // 添加商品到购物车
    addToCart(state, product) {
      const existingItem = state.cart.find(item => item.productId === product.productId)
      if (existingItem) {
        existingItem.quantity += product.quantity || 1
      } else {
        state.cart.push({
          ...product,
          quantity: product.quantity || 1,
          selected: true
        })
      }
      // 保存到localStorage
      localStorage.setItem('cart', JSON.stringify(state.cart))
    },
    
    // 从购物车移除商品
    removeFromCart(state, productId) {
      state.cart = state.cart.filter(item => item.productId !== productId)
      localStorage.setItem('cart', JSON.stringify(state.cart))
    },
    
    // 更新购物车商品数量
    updateCartItemQuantity(state, { productId, quantity }) {
      const item = state.cart.find(item => item.productId === productId)
      if (item) {
        item.quantity = quantity
        if (quantity <= 0) {
          state.cart = state.cart.filter(item => item.productId !== productId)
        }
      }
      localStorage.setItem('cart', JSON.stringify(state.cart))
    },
    
    // 更新购物车选择状态
    updateCartSelection(state, { items, selectAll }) {
      if (selectAll !== undefined) {
        state.cart.forEach(item => {
          item.selected = selectAll
        })
      } else if (items) {
        items.forEach(({ productId, selected }) => {
          const item = state.cart.find(item => item.productId === productId)
          if (item) {
            item.selected = selected
          }
        })
      }
      localStorage.setItem('cart', JSON.stringify(state.cart))
    },
    
    // 设置购物车数据
    setCart(state, cartData) {
      state.cart = cartData || []
      localStorage.setItem('cart', JSON.stringify(state.cart))
    },
    
    // 清空购物车
    clearCart(state) {
      state.cart = []
      localStorage.removeItem('cart')
    },
    
    // 设置结算商品
    setCheckoutItems(state, items) {
      state.checkoutItems = items || []
      localStorage.setItem('checkoutItems', JSON.stringify(state.checkoutItems))
    },
    
    // 设置商品分类
    setCategories(state, categories) {
      state.categories = categories
    },
    
    // 设置加载状态
    setLoading(state, loading) {
      state.loading = loading
    },
    
    // 初始化状态（从localStorage恢复）
    initializeStore(state) {
      // 恢复用户信息
      const user = localStorage.getItem('user')
      if (user) {
        try {
          const userData = JSON.parse(user)
          if (userData && userData.userId) {
            state.user = userData
            state.isLoggedIn = true
            console.log('从localStorage恢复用户信息:', userData.username)
          } else {
            localStorage.removeItem('user')
          }
        } catch (error) {
          console.error('解析用户信息失败:', error)
          localStorage.removeItem('user')
        }
      }
      
      // 恢复管理员信息
      const admin = localStorage.getItem('admin')
      if (admin) {
        try {
          state.admin = JSON.parse(admin)
          state.isAdminLoggedIn = true
        } catch (error) {
          console.error('解析管理员信息失败:', error)
          localStorage.removeItem('admin')
        }
      }
      
      // 恢复购物车
      const cart = localStorage.getItem('cart')
      if (cart) {
        try {
          state.cart = JSON.parse(cart)
        } catch (error) {
          console.error('解析购物车数据失败:', error)
          localStorage.removeItem('cart')
          state.cart = []
        }
      }
      
      // 恢复结算商品
      const checkoutItems = localStorage.getItem('checkoutItems')
      if (checkoutItems) {
        try {
          state.checkoutItems = JSON.parse(checkoutItems)
        } catch (error) {
          console.error('解析结算商品数据失败:', error)
          localStorage.removeItem('checkoutItems')
          state.checkoutItems = []
        }
      }
    }
  },
  
  actions: {
    // 初始化应用
    initializeApp({ commit }) {
      commit('initializeStore')
    },
    
    // 用户登录
    async loginUser({ commit }, userData) {
      commit('setUser', userData)
    },
    
    // 管理员登录
    async loginAdmin({ commit }, adminData) {
      commit('setAdmin', adminData)
    },
    
    // 用户登出
    async logoutUser({ commit }) {
      commit('logout')
      commit('clearCart') // 登出时清空购物车
    },
    
    // 管理员登出
    async logoutAdmin({ commit }) {
      commit('adminLogout')
    },
    
    // 添加商品到购物车
    addProductToCart({ commit }, product) {
      commit('addToCart', product)
    },
    
    // 从购物车移除商品
    removeProductFromCart({ commit }, productId) {
      commit('removeFromCart', productId)
    },
    
    // 更新购物车商品数量
    updateCartQuantity({ commit }, payload) {
      commit('updateCartItemQuantity', payload)
    },
    
    // 更新购物车选择状态
    updateCartSelection({ commit }, payload) {
      commit('updateCartSelection', payload)
    },
    
    // 从localStorage加载购物车
    loadCartFromStorage({ commit }) {
      const cart = localStorage.getItem('cart')
      if (cart) {
        try {
          const cartData = JSON.parse(cart)
          commit('setCart', cartData)
        } catch (error) {
          console.error('加载购物车失败:', error)
          commit('setCart', [])
        }
      }
    },
    
    // 设置商品分类
    updateCategories({ commit }, categories) {
      commit('setCategories', categories)
    }
  },
  
  modules: {
    // 可以在这里添加模块
  }
})
